package com.roadjava.rbac.security;

import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class LoginAttemptService {
    private final int MAX_ATTEMPT = 5;         // 最大失败次数
    private final long BLOCK_TIME = 300000;    // 阻止时间，单位毫秒（此处设置为5分钟）

    private final ConcurrentHashMap<String, Integer> attemptsCache = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, Long> blockCache = new ConcurrentHashMap<>();

    public void loginSucceeded(String username) {
        attemptsCache.remove(username);
        blockCache.remove(username); // 登录成功后，也移除阻止时间
    }

    public void loginFailed(String username) {
        attemptsCache.put(username, attemptsCache.getOrDefault(username, 0) + 1);
        if (attemptsCache.get(username) >= MAX_ATTEMPT) {
            blockCache.put(username, System.currentTimeMillis()); // 记录被阻止的时间
        }
    }

    public boolean isBlocked(String username) {
        if (blockCache.containsKey(username)) {
            long blockTime = blockCache.get(username);
            if (System.currentTimeMillis() - blockTime < BLOCK_TIME) {
                return true; // 仍在被阻止期间
            } else {
                // 超过被阻止时间，移除记录
                blockCache.remove(username);
                attemptsCache.remove(username); // 也可以选择移除失败计数
            }
        }
        return false; // 没有被阻止
    }
}
